package cn.buglife.concurrent.threadpool;

import java.util.concurrent.*;

/**
 * @author zhangjun
 */
public class ThreadPoolSample {

  public static void main(String[] args) {
    ExecutorService executorService = Executors.newFixedThreadPool(5);

    // execute(Runnable) 方法要求一个 java.lang.Runnable 对象，然后对它进行异步执行
    executorService.execute(() -> System.out.println("java") );

    // Future 对象可以用来检查 Runnable 是否已经执行完毕。
    Future future = executorService.submit(() -> System.out.println("hello java") );

    try {
      // returns null if the task has finished correctly.
      System.out.println(future.get());
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }

    int corePoolSize = 5;
    int maxPoolSize = 10;
    long keepAliveTime = 5000;

    ExecutorService threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize,
        keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<> ());

    threadPoolExecutor.execute(() -> System.out.println(Thread.currentThread().getName() + ": hello") );
    threadPoolExecutor.execute(() -> System.out.println(Thread.currentThread().getName() + ": hello") );
    threadPoolExecutor.execute(() -> System.out.println(Thread.currentThread().getName() + ": hello") );
    threadPoolExecutor.execute(() -> System.out.println(Thread.currentThread().getName() + ": hello") );
    threadPoolExecutor.execute(() -> System.out.println(Thread.currentThread().getName() + ": hello") );
  }
}
